package dao.impl;

import java.util.Date;
import java.util.List;

import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bean.Article;

import dao.ArticleDao;

public class ArticleDaoImpl extends HibernateDaoSupport implements ArticleDao {

	@Override
	public boolean addArticle(Article article) {
		this.getSessionFactory().getCurrentSession().save(article);
		return true;
	}

	@Override
	public boolean modifyArticle(Article article) {
		// TODO Auto-generated method stub
		this.getSessionFactory().getCurrentSession().update(article);
		return true;
	}

	@Override
	public boolean deleteArticle(Article article) {
		this.getSessionFactory().getCurrentSession().delete(article);
		return true;
	}

	@Override
	public Article findArticleById(int id) {
		Object o=this.getSessionFactory().getCurrentSession().load(Article.class, id);
		if(o==null)
		return null;
		else
			return (Article) o;
	}

	@Override
	public List findArticlesByDate(Date date) {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().createCriteria(Article.class).add(Restrictions.eq("time", date)).list();
		return l;
	}

	@Override
	public List findArticlesByView(int view) {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().createCriteria(Article.class).add(Restrictions.gt("visit", view)).list();
		return l;
	}

	@Override
	public List findArticlesByUsername(String username) {
		List l=this.getSessionFactory().getCurrentSession().find("from article a where a.user.username='"+username+"'");
		return l;
	}

	@Override
	public List findArticlesByArticleClassId(int id) {
		List l=this.getSessionFactory().getCurrentSession().createCriteria(Article.class).add(Restrictions.eq("articleClass.id", id)).list();
		return l;
	}

	@Override
	public List findArticlesByTitle(String name) {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().createCriteria(Article.class).add(Restrictions.like("title", "%"+name+"%")).list();
		return l;
	}

	@Override
	public List findRecentArticles() {
		// TODO Auto-generated method stub
		List l=this.getSessionFactory().getCurrentSession().find("from Article a order by id desc");
		if(l.size()>5)
			return l.subList(0, 5);
		else
			return l;
	}

}
